package com.vcens.dingnotice.rest.v1;

import com.alibaba.fastjson.JSON;
import com.vcens.dingnotice.entity.MessageEntity;
import com.vcens.dingnotice.service.impl.MessageServiceImpl;
import com.vcens.dingnotice.utils.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author VeChar
 * @Desc 消息控制器
 * @CreateTime 2018/9/30 11:01 AM
 **/
@RestController
@Slf4j
@RequestMapping("/api/v1.0/job")
public class JobController {

    @Autowired
    private MessageServiceImpl messageService;

    /**
     * 创建ActionCardMessage消息
     *
     * @param request
     * @param msgType 钉钉卡片消息类型
     * @return
     */
    @PostMapping("actionCard/create/{msgType}")
    public DataResult create(HttpServletRequest request, @PathVariable Integer msgType) {
        Map<String, Object> paramMap = new HashMap<>();
        Map<String, String[]> requestMap = request.getParameterMap();
        Iterator<Map.Entry<String, String[]>> it = requestMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String[]> entry = it.next();
            if (entry.getValue().length == 1) {
                paramMap.put(entry.getKey(), entry.getValue()[0]);
            } else {
                String[] values = entry.getValue();
                String value = "";
                for (int i = 0; i < values.length; i++) {
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length() - 1);
                paramMap.put(entry.getKey(), value);
            }
        }
        paramMap.put("MsgType", msgType);
        MessageEntity messageEntity = new MessageEntity();
        messageEntity.setContent(JSON.toJSONString(paramMap));
        messageEntity.setCreateTime(new Date());
        messageEntity.setUpdateTime(new Date());
        messageEntity.setTaskId(Integer.parseInt(paramMap.get("taskId").toString()));
        messageEntity.setTypeId(Integer.parseInt(paramMap.get("typeId").toString()));

        messageService.insert(messageEntity);
        return null;
    }
}
